package com.aube.interact.fighter.card;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aube.interact.fighter.R;
import com.aube.interact.fighter.control.DataManager;
import com.aube.interact.fighter.model.GameConfig;
import com.aube.interact.fighter.model.OptionItem;
import com.aube.interact.fighter.model.OptionResultModel;
import com.aube.interact.fighter.model.ReportResultModel;
import com.aube.interact.fighter.model.TimeLinePiece;
import com.aube.interact.fighter.roundedimageview.RoundedImageView;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.video.model.GoodsItem;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/11/15.
 */
public class CardQA extends BaseCardNew {

    private LinearLayout mQALayout;
    private View mDivider;

    private AtomicBoolean mCallSended = new AtomicBoolean(false);
    private AtomicBoolean mRevealResult = new AtomicBoolean(false);
    private int mRightAnswerIndex = -1;

    private int selectedIndex = -1;

    private int mTotal = 0;

    private String mMessage = null;
    private List<GoodsItem> mGoodsList = null;
    private float[] mLabel;

    private View[] mQAOptions;

    private int mCardWidthMin=0;
    private int mCardTotalSpace=0;

    private boolean isImgInOption = false;

    public CardQA(Context context) {
        this(context, null);
    }

    public CardQA(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CardQA(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        LayoutInflater.from(context).inflate(R.layout.aube_intera_card_qa, this, true);

        mTitle = (TextView) findViewById(R.id.card_title);
        mDesp = (TextView) findViewById(R.id.card_desp);
        mFoldStateTxt = (TextView) findViewById(R.id.card_foldorexpand_text);

        mCollapse = (ImageView) findViewById(R.id.card_foldorexpand_img);
        mDespLayout = findViewById(R.id.card_desp_layout);

        mQALayout = (LinearLayout) findViewById(R.id.card_detail_layout);

        mDivider = findViewById(R.id.card_divider);

        mClose = (ImageView) findViewById(R.id.card_close);
        mClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

        mDespLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                swithWindow(mQALayout.getVisibility() == View.VISIBLE, mQALayout);
            }
        });

        mCardWidthMin = getResources().getDimensionPixelOffset(R.dimen.card_width_min);
        mCardTotalSpace = getResources().getDimensionPixelOffset(R.dimen.card_total_space);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(mCardWidthMin, MeasureSpec.EXACTLY);
        if(isImgInOption) {
            mQALayout.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            if (mContentHeight <= 0) {
                mContentHeight = mQALayout.getMeasuredHeight();
            }
            int width = measure(widthMeasureSpec);
            if (width - mCardTotalSpace < mQALayout.getMeasuredWidth())
                widthMeasureSpec = MeasureSpec.makeMeasureSpec(mQALayout.getMeasuredWidth() + mCardTotalSpace, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if(!isImgInOption) {
            if (mContentHeight <= 0) {
                mContentHeight = mQALayout.getMeasuredHeight();
            }
        }
    }

    @Override
    public void init(TimeLinePiece data, ChannelDetail channelDetail) {
        super.init(data, channelDetail);

        selectedIndex = DataManager.getInstance(getContext()).getIndex(mData.rid);

        mTitle.setText(data.title);

        setupLabels();
        fillData();

        if (data.isCardFold()) {
            mQALayout.setVisibility(View.GONE);
            mDivider.setVisibility(View.VISIBLE);
        }
        switchFoldState(!data.isCardFold());

        UmengUtils.reportUmengEvent(mContext, UmengUtils.SHOW_QA, UmengUtils.appendLabels(mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
    }

    private void fillData() {
        if (mLabel == null)
            return;
        mQAOptions = new View[mLabel.length];

        isImgInOption = mData.hasImgInOption();
        mDivider.setVisibility(isImgInOption ? View.VISIBLE : View.INVISIBLE);
        for (int i = 0; i < mLabel.length; i++) {
            if(isImgInOption) {
                mQALayout.setOrientation(HORIZONTAL);
                View view = LayoutInflater.from(mContext).inflate(R.layout.aube_intera_option_item, null, false);
                mQALayout.addView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                updateItemWidthImg(view, mLabel[i], i);
                mQAOptions[i] = view;
            } else {
                mQALayout.setOrientation(VERTICAL);
                View view = LayoutInflater.from(mContext).inflate(R.layout.aube_intera_radio_item, null, false);
                mQALayout.addView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                updateItemWithRadio(view, mLabel[i], i);
                mQAOptions[i] = view;
            }
        }
    }

    @Override
    protected void showDivider() {
        if(isImgInOption)
            return;
        mDivider.setVisibility(View.VISIBLE);
    }

    @Override
    protected void hideDivider() {
        if(isImgInOption)
            return;
        mDivider.setVisibility(View.INVISIBLE);
    }

    private void updateItem(View view, float value, int index) {
        if(isImgInOption)
            updateItemWidthImg(view, value, index);
        else
            updateItemWithRadio(view, value, index);
    }

    private void updateItemWidthImg(View view, float value, int index) {
        TextView mTitle = (TextView) view.findViewById(R.id.option_detail);
        final ImageView mState = (ImageView) view.findViewById(R.id.option_state);
        RoundedImageView mImg = (RoundedImageView) view.findViewById(R.id.option_img);
        final View mOptionBg = view.findViewById(R.id.option_bg);
        TextView mRatio = (TextView) view.findViewById(R.id.option_ratio);
        mRatio.setText(((int) value*100) + "%");

        ImageLoader.getInstance(getContext()).fillImage(mImg, mData.getOptionImgUrl(index));

        mTitle.setText(mData.getOptionValue(index));
        mState.setTag(index);

        //答案出来了之后再显示img
        if (index == selectedIndex) {
            mOptionBg.setVisibility(View.VISIBLE);
        } else {
            mOptionBg.setVisibility(View.GONE);
        }

        if(selectedIndex >= 0) {
            mRatio.setVisibility(View.VISIBLE);
            if (mRevealResult.get()) {
                mState.setVisibility(View.VISIBLE);
                GameConfig config = iSender.getConfig();
                if (mRightAnswerIndex == index) {
                    //right
                    mState.setImageResource(R.drawable.icon_right);

                    if(iSender != null)
                        iSender.addFragment(mData.getRid());

                    //fill prizetext
                    if(config != null)
                        fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
                } else {
                    if(selectedIndex == index) {
                        //wrong
                        mState.setImageResource(R.drawable.icon_wrong);

                        //fill prizetext
                        if (config != null)
                            fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
                    }
                }
            }
        }

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (int) mState.getTag();
                if (selectedIndex != index) {
                    try {
                        if (mRevealResult.get())
                            return;

                        DataManager.getInstance(getContext()).update(mData.rid, index);

                        String cancelId = null;
                        String optionId = mData.getOptionId(index);

                        reportOptionSelectEvent("option", optionId);

                        if (selectedIndex >= 0)
                            cancelId = mData.getOptionId(selectedIndex);
                        if (mData == null)
                            Toast.makeText(getContext(), mData.getOptionValue(index), Toast.LENGTH_SHORT).show();
                        else
                            report(mData.rid, optionId, cancelId, false);

                        DataManager.getInstance(getContext()).updateOptionCount(cancelId, true);
                        DataManager.getInstance(getContext()).updateOptionCount(optionId, false);

                        UmengUtils.reportUmengEvent(getContext(), UmengUtils.TO_QA, UmengUtils.appendLabels(mData.getOptionValue(index), mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (selectedIndex >= 0) {
                        updateItem(selectedIndex, false);
                    }

                    mState.setImageResource(R.drawable.icon_selected);
                    selectedIndex = index;
                    mOptionBg.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void updateItemWithRadio(View view, float value, int index) {
        TextView mTitle = (TextView) view.findViewById(R.id.radio_title);
        final ImageView mState = (ImageView) view.findViewById(R.id.radio_state);
        VoteProgressView mProgress = (VoteProgressView) view.findViewById(R.id.radio_progress);

        TextView mDesc = (TextView) view.findViewById(R.id.radio_desc);
        mDesc.setText(((int) value*100) + "%");

        mTitle.setText(mData.getOptionValue(index));
        mProgress.updateProgress(value, true);
        mState.setTag(index);

        //答案出来了之后再显示img
        if (index == selectedIndex) {
            if (mRevealResult.get()) {
                GameConfig config = iSender.getConfig();
                if (mRightAnswerIndex == index) {
                    //right
                    mState.setImageResource(R.drawable.icon_right);

                    if(iSender != null)
                        iSender.addFragment(mData.getRid());

                    //fill prizetext
                    if(config != null)
                        fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
                } else {
                    //wrong
                    mState.setImageResource(R.drawable.icon_wrong);

                    //fill prizetext
                    if(config != null)
                        fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
                }
            } else {
                mState.setImageResource(R.drawable.icon_selected);
            }
        } else {
            mState.setImageResource(R.drawable.icon_select);
        }

        mState.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (int) mState.getTag();
                if (selectedIndex != index) {
                    try {
                        if (mRevealResult.get())
                            return;

                        DataManager.getInstance(getContext()).update(mData.rid, index);

                        String cancelId = null;
                        String optionId = mData.getOptionId(index);

                        reportOptionSelectEvent("option", optionId);

                        if (selectedIndex >= 0)
                            cancelId = mData.getOptionId(selectedIndex);
                        if (mData == null)
                            Toast.makeText(getContext(), mData.getOptionValue(index), Toast.LENGTH_SHORT).show();
                        else
                            report(mData.rid, optionId, cancelId, false);

                        DataManager.getInstance(getContext()).updateOptionCount(cancelId, true);
                        DataManager.getInstance(getContext()).updateOptionCount(optionId, false);

                        UmengUtils.reportUmengEvent(getContext(), UmengUtils.TO_QA, UmengUtils.appendLabels(mData.getOptionValue(index), mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (selectedIndex >= 0) {
                        updateItem(selectedIndex, false);
                    }

                    mState.setImageResource(R.drawable.icon_selected);
                    selectedIndex = index;
                }
            }
        });
    }

    private void updateItem(int selectedIndex, boolean selected) {
        ImageView mState = (ImageView) mQAOptions[selectedIndex].findViewById(R.id.radio_state);
        if(mState != null)
            mState.setImageResource(selected ? R.drawable.icon_selected : R.drawable.icon_select);
        View mOptionBg = mQAOptions[selectedIndex].findViewById(R.id.option_bg);
        if(mOptionBg != null)
            mOptionBg.setVisibility(View.GONE);
    }

    public void doNext() {
        if (selectedIndex >= 0) {
            mDesp.setText("");
            mRevealResult.set(true);

            //已选的结果直接展示出来,除非有中奖提示
            String msg = DataManager.getInstance(getContext()).getQAResult(mData.rid);
            if (StringUtils.isNotBlank(msg)) {
//                mQAResult.setVisibility(View.VISIBLE);
            }

            setupLabels();

            if (iSender != null)
                iSender.startSync(mData.rid, false);

            updateOptions();
        }
    }

    public void updateCountDown(String time) {
        if (mRevealResult.get())
            return;
        mDesp.setText(time);

        if (iSender != null && mData != null && StringUtils.isBlank(time) && !mCallSended.get()) {
            mCallSended.set(true);
            mRevealResult.set(true);
            iSender.startSync(mData.rid, false);
            updateOptions();

            //当有奖品的时候才提示
//            if (StringUtils.isNotBlank(mMessage) && mGoodsList != null && mGoodsList.size() > 0)
//                animResult(mMessage);
        }
    }

    private void updateOptions() {
        if (mQAOptions != null && mLabel != null) {
            for (int i = 0; i < mQAOptions.length; i++) {
                updateItem(mQAOptions[i], mLabel[i], i);
            }
        }

        if (mRevealResult.get())
            mDesp.setText(mTotal + "人参与");
    }

    @Override
    public String getType() {
        return TYPE_QA;
    }

    @Override
    public void syncData(OptionResultModel response) {
        try {
            setupLabels();
            updateOptions();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void syncPreviewData(ReportResultModel result) {

    }

    @Override
    public boolean IsPreviewDataSynced() {
        return false;
    }

    public void report(String rid, String msg, List<GoodsItem> goodsItemList) {
        String id = DataManager.getInstance(mContext).getSelectedOptionId(mData.rid);
        if (StringUtils.isNotBlank(id) && id.equalsIgnoreCase(rid)) {
            mMessage = msg;
            mGoodsList = goodsItemList;

            if (DataManager.getInstance(getContext()).update(mGoodsList)) {
                DataManager.getInstance(getContext()).updateQAResult(rid, msg);

                //将奖品加入到商品列表当中
                if (iSender != null)
                    iSender.onAddRewardGoods(mGoodsList);
            }
        } else {
            mMessage = null;
            mGoodsList = null;
        }
    }

    private synchronized void setupLabels() {
        if (mData == null)
            return;
        HashMap<String, Float> mSet = new HashMap<>();
        mTotal = 0;
        for (OptionItem item : mData.getOptions()) {
            mTotal += DataManager.getInstance(mContext).getOptionCount(item.optionId);
        }

        if (mTotal > 0) {
            for (OptionItem item : mData.getOptions()) {
                mSet.put(item.optionId, Utils.calPercentFloat(mTotal, DataManager.getInstance(mContext).getOptionCount(item.optionId)));
            }

            reSortData(mSet);
        }
        mLabel = new float[mData.optionSize()];
        int index = 0;
        for (OptionItem item : mData.getOptions()) {
            mLabel[index] = mSet.containsKey(item.optionId) ? mSet.get(item.optionId) : 0;

            if (mRightAnswerIndex < 0) {
                //find the right answer
                if (item.isRightAnswer())
                    mRightAnswerIndex = index;
            }

            index++;
        }
    }

}
